package com.coocaa.x.app.hall.view.widget.loading;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;

import com.coocaa.x.app.hall.R;

/**
 * Created by luwei on 15-7-10.
 */
public class CircleLoading extends View {

    private Paint paint = new Paint();
    private boolean isLoading = false;
    private int initArc = -90;
    private int addStepArc = 3;
    private int roStepArc = 8;
    private int arc = 200;
    private int width = 7;
    private boolean addArc = false;
    private int preColor = 0;
    private int backColor = 0x456b6b6b;

    public CircleLoading(Context context) {
        super(context);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setAntiAlias(true);
        preColor = getResources().getColor(R.color.cpv_default_color);
        width = getResources().getDimensionPixelSize(R.dimen.cpv_default_thickness);
        paint.setStrokeWidth(width);
    }


    public void startAnimation() {
        isLoading = true;
        invalidate();
    }


    public void stopAnimation() {
        isLoading = false;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int centerX = getWidth() / 2;
        int centerY = getHeight() / 2;
        int radius = centerX - 21;
        paint.setColor(backColor);
        canvas.drawCircle(centerX, centerY, radius, paint);
        paint.setColor(preColor);
        canvas.drawArc(new RectF(centerX - radius,
                centerY - radius,
                centerX + radius,
                centerY + radius), initArc, arc, false, paint);
        if (isLoading) {
            initArc += roStepArc;
            if (!addArc) {
                arc -= addStepArc;
            } else if (addArc) {
                arc += addStepArc;
            }
            if (initArc > 270) {
                initArc = initArc - 360;
            }
            if (arc >= 200)
                addArc = false;
            else if (arc <= 20)
                addArc = true;
            invalidate();
        }
        super.onDraw(canvas);
    }
}
